﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UsersProvider.Repositories.RelationalRepositories
{
    public class EventCommentsRepository : IEventCommentsRepository
    {
        /// <summary>
        /// Gets comments list from event id
        /// </summary>
        /// <param name="eventId">Event Id</param>
        /// <returns></returns>
        public IEnumerable<Comments> GetComments(int eventId)
        {
            using (UsersModelEntities context = new UsersModelEntities())
            {
               // return context.CommentSet.Include("User")
               //.Where(c => c.EventId == eventId)
               //.OrderByDescending(c => c.Date)
               //.ToList();
                return context.CommentSet.Include("User")
               .Where(c => c.EventId == eventId)
               .ToList();
            }
        }

        /// <summary>
        /// Posts a comment for an event
        /// </summary>
        /// <param name="username"></param>
        /// <param name="comment"></param>
        public void PostComment(int eventid, string username, string comment)
        {
            using (UsersModelEntities context = new UsersModelEntities())
            {
                User user = context.UserSet.FirstOrDefault(u => u.Login == username);
                if (user == null) throw new RepositoryOperationFailedException("Failed to find a user");

                Comments aComment = new Comments
                {
                    User = user,
                    EventId = eventid,
                    Comment = comment,
                    Date = DateTimeOffset.UtcNow.UtcDateTime
                };

                context.AddToCommentSet(aComment);
                context.SaveChanges();
            }
        }
    }
}
